package com.genoworks.gcconsole;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.LinkedList;
import java.util.List;

public class GcReader implements Runnable {

  private BufferedReader reader = null;

  private final List<GcListener> listeners = new LinkedList<GcListener>();

  public GcReader( Reader r ) {
    if ( r instanceof BufferedReader ) {
      reader = ( (BufferedReader) r );
    } else {
      reader = new BufferedReader( r );
    }
  }

  public void addCollectionListener( GcListener listener ) {
    listeners.add( listener );
  }

  public void removeCollectionListener( GcListener listener ) {
    listeners.remove( listener );
  }

  public void run() {
    try {
      while ( true ) {
        String line = reader.readLine();
        if ( line == null ) {
          return;
        }

        //
        GcEvent event = GcParser.parseLine( line );
        if ( event == null ) {
          // TODO
          continue;
        }
        for ( GcListener listener : listeners ) {
          try {
            listener.onGarbageCollection( event );
          } catch( Throwable t ) {
          }
        }
      }
    } catch( IOException e ) {
      // TODO
      e.printStackTrace();
    }
  }

  public static void main( String[] args ) {

    /**
     * 옵션 처리.
     */

    // 1. numcol
    int numCols = -1;
    if ( args.length >= 2 ) {
      if ( args[ 0 ].equals( "-numcol" ) ) {
        try {
          numCols = Integer.parseInt( args[ 1 ] );
        } catch( Throwable t ) {
          System.out.println( "Invalid number of columns" );
          System.exit( 0 );
        }
      } else {
        System.out.println( "Unknown option " + args[ 0 ] );
        System.exit( 0 );
      }
    }

    //
    GcReader rd = new GcReader( new InputStreamReader( System.in ) );
    GcListener writer = new ConsoleWriter( System.out );
    if ( numCols > 0 && writer instanceof ConsoleWriter ) {
      ( (ConsoleWriter) writer ).setNumberOfColumns( numCols );
    }
    rd.addCollectionListener( writer );
    new Thread( rd ).start();
  }
}
